<template>
  <SlideViewSingle v-if="id && visible"
                   :body-style="{padding: 0, height: '100%'}"
                   class="d-view"
                   @afterEnter="viewAfterEnter"
                   @close="hideView">
    <div v-loading="crmOption.loading" ref="crmDetailMain" class="detail-main">
      <flexbox v-if="canShowDetail && detailData" direction="column"
               align="stretch" class="d-container">
        <SzDetailHeadSingle
            :detail="detailData"
            :head-details="headDetails"
            :id="id"
            :crm-type="crmOption.crmType"
            :page-list="pageList"
            @pageChange="pageChange"
            @handle="detailHeadHandle"
            @close="hideView"/>
        <flexbox class="d-container-bd" align="stretch">
          <el-tabs v-model="currentTabName" type="border-card" class="d-container-bd--left">
            <el-tab-pane v-for="(item, index) in tabNames" :key="index"
                         :label="item.label" :name="item.name" lazy>
              <component :is="item.comp"
                         :detail="detailData"
                         :type-list="logTypes"
                         :handle="activityHandle"
                         :id="id"
                         :crm-type="crmOption.crmType"
                         @handle="detailHeadHandle"/>
            </el-tab-pane>
          </el-tabs>
          <transition name="slide-fade">
            <el-tabs v-show="showImportInfo"
                     value="chiefly-contacts"
                     type="border-card"
                     class="d-container-bd--right">
              <el-tab-pane label="重要信息"
                           name="chiefly-contacts"
                           lazy>
                <ChieflyContacts :id="id" :customer-id="customerId"/>
              </el-tab-pane>
            </el-tabs>
          </transition>
        </flexbox>
      </flexbox>
    </div>
    <el-button class="firse-button"
               @click="showImportInfo= !showImportInfo">
      重<br>要<br>信<br>息<br>
      <i :class="{ 'is-reverse': !showImportInfo }" class="el-icon-arrow-right el-icon--right"/>
    </el-button>

<!--    此处是编辑-->
    <ContactsCreate v-if="showEditDialog"
                    :action="{type: 'update', id: id, batchId: detailData.batchId, editDetail: detailData}"
                    :crm-type="crmOption.crmType"
                    @save-success="editSaveSuccess"
                    @close="showEditDialog=false"/>
  </SlideViewSingle>
</template>

<script setup>
import CRMEditBaseInfo from '/src/views/crm/componentsNew/BaseInfo/CRMEditBaseInfo.vue' // 产品基本信息
import RelativeFiles from '/src/views/crm/componentsNew/relative/RelativeFiles.vue' // 相关附件
import RelativeHandle from '/src/views/crm/componentsNew/relative/RelativeHandle.vue' // 相关操作
import {crmOptionKey} from "@/views/crm/componentsNew/SzCrud/keys.js";
import SlideViewSingle from "@/views/crm/componentsNew/SzCrud/SlideView.vue";
import SzDetailHeadSingle from "@/views/crm/componentsNew/SzCrud/detail/SzDetailHead.vue";
import {filedGetInformationAPI} from "@/api/crm/common.js";
import crmTypeModel from "@/views/crm/model/crmTypeModel.js";
import {useSzTab} from "@/views/crm/componentsNew/SzCrud/detail/useSzTab.js";
import {useSzDetail} from "@/views/crm/componentsNew/SzCrud/detail/useSzDetail.js";
import {ElMessage} from "element-plus"
import {getCurrentInstance} from 'vue'
import ChieflyContacts from "@/views/crm/contacts/components/ChieflyContacts.vue";
import RelativeTeam from "@/views/crm/componentsNew/relative/RelativeTeam.vue";
import RelativeBusiness from "@/views/crm/componentsNew/relative/RelativeBusiness.vue";
import ActivitySingle from "/src/views/crm/componentsNew/ActivityNew/index.vue"
import {useErpUserStore} from "@/store/modules/usererp.js";
import {crmContactsReadAPI} from "@/api/crm/contacts.js";
import ContactsCreate from "./Create.vue"

defineOptions({
  // 客户管理 的 产品详情
  name: 'ContactsDetail',
})
const props = defineProps({
  visible: Boolean,
  // 详情信息id
  id: [String, Number],
  // 表示第几个详情
  pageIndex: [String, Number],
  // 用于详情切换
  pageList: Array,
  crmOptionChange: Function
})

const showImportInfo = ref(true)
// 从store中拿到crm权限
const crm = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.crm
})

// 下面的headDetails、tabNames、activityHandle、getDetail需要自定义，不能放在SzDetail中
const headDetails = reactive([
  {title: '客户名称', value: ''},
  {title: '职务', value: ''},
  {title: '手机', value: ''},
  {title: '创建时间', value: ''}
])

const tabNames = computed(() => {
  var tempsTabs = []
  tempsTabs.push({label: '活动', name: 'Activity', comp: ActivitySingle})
  if (crm.value.contacts && crm.value.contacts.read) {
    tempsTabs.push({label: '详细资料', name: 'CRMEditBaseInfo', comp: CRMEditBaseInfo})
  }

  tempsTabs.push({
    label: getTabName('团队成员', tabsNumber.value.memberCount),
    name: 'RelativeTeam',
    comp: RelativeTeam
  })

  if (crm.value.business && crm.value.business.index) {
    tempsTabs.push({
      label: getTabName('商机', tabsNumber.value.businessCount),
      name: 'RelativeBusiness',
      comp: RelativeBusiness
    })
  }
  tempsTabs.push({
    label: getTabName('附件', tabsNumber.value.fileCount),
    name: 'RelativeFiles',
    comp: RelativeFiles
  })
  tempsTabs.push({label: '操作记录', name: 'RelativeHandle', comp: RelativeHandle})
  return tempsTabs
})

/**
 * 根据记录筛选。只有存在Activity的时候，才需要logTypes
 */
const logTypes = computed(() => {
  return [{
    icon: 'all',
    color: '#2362FB',
    command: '',
    label: '全部活动'
  }, {
    icon: 'contacts',
    color: '#27BA4A',
    command: 3,
    label: '联系人'
  }, {
    icon: 'o-task',
    color: '#D376FF',
    command: 11,
    label: '任务'
  }, {
    icon: 'log',
    color: '#5864FF',
    command: 8,
    label: '日志'
  }, {
    icon: 'approve',
    color: '#9376FF',
    command: 9,
    label: '审批'
  }]
})

// 是否能新建跟进记录
const canCreateFollowRecord = computed(() => {
  return crm.value && crm.value.followRecord && crm.value.followRecord.save
})

/**
 * 活动操作
 */
const activityHandle = computed(() => {
  let temps = [
    {
      type: 'task',
      label: '创建任务'
    }, {
      type: 'business',
      label: '创建商机'
    }, {
      type: 'contract',
      label: '创建合同'
    }, {
      type: 'receivables',
      label: '创建回款'
    }
  ]

  if (canCreateFollowRecord) {
    temps = [{
      type: 'log',
      label: '写跟进'
    }].concat(temps)
  }

  return temps
})

const emits = defineEmits(['update:pageIndex', 'update:visible',
  'crm-detail-update', 'update:id', 'handle', 'crm-tab-num-update', 'hide-view'])

const crmOption = inject(crmOptionKey)
const {currentTabName, tabsNumber, getTabsNum, getTabName}
    = useSzTab(crmOption, toRef(() => props.id))
const {detailData, canShowDetail} = useSzDetail(crmOption)

const detailOption = reactive({
  currentTabName,
  tabsNumber, getTabsNum, getTabName, detailData, canShowDetail
})

/**
 * 客户ID
 */
const customerId = computed(() => {
  return detailData ? detailData.customerId || '' : ''
})

currentTabName.value = 'Activity'


// 在detail.vue中
watch(() => props.id, () => {
  if (canShowDetail && canShowDetail.value) {
    detailData.value = null
    tabsNumber.value = {}
    getDetail()
    getTabsNum()
  }
})

const mainFileList = computed(() => {
  if (detailData && detailData.mainFileList) {
    return detailData.mainFileList
  }

  return []
})

const detailFileList = computed(() => {
  if (detailData && detailData.detailFileList) {
    return detailData.detailFileList
  }

  return []
})

/**
 * 详情
 */
function getDetail() {
  crmOption.loading = true
  crmContactsReadAPI({contactsId: props.id}).then(res => {
    console.log("res", res)
    detailData.value = res.data.data

    headDetails[0].value = res.data.data.customerName
    headDetails[1].value = res.data.data.post
    headDetails[2].value = res.data.data.mobile
    headDetails[3].value = res.data.data.createTime

    crmOption.loading = false
  }).catch((r) => {
    console.log("r", r)
    crmOption.loading = false
    hideView()
  })

}

/**
 * 进入详情页面后的动作
 */
function viewAfterEnter() {
  if (canShowDetail.value) {
    getDetail()
    getTabsNum()
    bus.on('crm-tab-num-update', getTabsNum)
  }
}

/**
 * 关闭
 */
function hideView() {
  emits('hide-view')
}

/**
 * 详情页面切换
 */
function pageChange(type) {
  let currentPageIndex = props.pageIndex
  if (type === 'left') {
    if (props.pageIndex > 0) {
      emits('update:pageIndex', --currentPageIndex)
      emits('update:id', props.pageList[currentPageIndex][`${crmOption.crmType}Id`])
    } else {
      ElMessage.error({message: '没有更多了！'})
    }
  } else {
    if (currentPageIndex < props.pageList.length - 1) {
      emits('update:pageIndex', ++currentPageIndex)
      emits('update:id', props.pageList[currentPageIndex][`${crmOption.crmType}Id`])
    } else {
      ElMessage.error({message: '没有更多了！'})
    }
  }
}


/**
 * 顶部头 操作
 * @param {*} data
 */
function detailHeadHandleClick(data) {
  // if (data.type === 'edit') {
  //   crmOption.createCRMType = 'customer'
  //   createActionInfo.value = {
  //     type: 'update',
  //     id: props.id,
  //     batchId: detailData.value.batchId
  //   }
  //   isCreate.value = true
  //   return false
  // }
}

// 编辑操作
const showEditDialog = ref(false)

/**
 * 顶部头 操作
 * @param {*} data
 */
function detailHeadHandle(data) {
  // 返回值为false 不继续执行
  if (detailHeadHandleClick(data) === false) {
    return
  }

  if (data.type === 'edit') {
    showEditDialog.value = true
    // props.crmOptionChange('isCreate', true)
    // props.crmOptionChange('createShow', true)
  } else if (data.type === 'delete' ||
      data.type === 'exit-team' ||
      data.type === 'alloc' ||
      data.type === 'get' ||
      data.type === 'transfer' ||
      data.type === 'transform' ||
      data.type === 'delete' ||
      data.type === 'put_seas') {
    hideView()
  } else if (data.type === 'state_start' ||
      data.type === 'state_disable' ||
      data.type === 'deal_status' ||
      data.type === 'cancel' ||
      data.type === 'examine') {
    getDetail()
  } else if (data.type === 'save-success') {
    // 但字段编辑成功刷新
    editSaveSuccess()
    return
  }

  emits('handle', data)
}

function editSaveSuccess() {
  emits('crm-detail-update', crmOption.crmType)
  emits('handle', {type: 'save-success'})
  detailOption.detailData = null
  getDetail()
}

</script>

<style lang="scss" scoped>
.image {
  color: #333;

  &-info {
    margin: 10px 25px 0;

    &__label {
      font-size: 13px;
    }

    &__list {
      overflow-x: auto;
      white-space: nowrap;

      img {
        margin-top: 15px;
        border-radius: $xr-border-radius-base;
        cursor: pointer;
      }

      img + img {
        margin-left: 20px;
      }

      .main-img {
        width: 100px;
        height: 76px;
        object-fit: contain;
        vertical-align: top;
      }

      .detial-img {
        width: 100px;
        height: 80px;
        object-fit: contain;
        vertical-align: top;
      }
    }
  }

  .no-img {
    color: #666;
    margin: 50px 0;
    text-align: center;
  }
}

@import '../styles/crmdetail';
</style>
